﻿using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System;

namespace VsExt.CollapseSolution
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package. GUID
    // This attribute is used to register the information needed to show the this package
    // in the Help/About dialog of Visual Studio.
    // This attribute is needed to let the shell know that this package exposes some menus.
    //[ProvideAutoLoad(Microsoft.VisualStudio.Shell.Interop.UIContextGuids80.SolutionExists)]
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidCollapseSolutionPkgString)]
    public sealed class VsExt_CollapseSolutionPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public VsExt_CollapseSolutionPackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "constructor for: {0}", this.ToString()));
        }

        private DTE2 Dte { get; set; }

        private UIHierarchy SolutionExplorer { get; set; }

        private MenuCommand SolutionExplorerToolbarCommand { get; set; }

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));

            base.Initialize();

            Dte = (DTE2)GetService(typeof(DTE));

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (null != mcs)
            {
                // Create the command for the menu item.
                CommandID menuCommandCollapseSolution = new CommandID(GuidList.guidCollapseSolutionCmdSet, (int)PkgCmdIDList.cmdidCollapseTree);
                MenuCommand menuItemSolution = new MenuCommand(MenuItemCallback, menuCommandCollapseSolution);
                mcs.AddCommand(menuItemSolution);

                CommandID menuCommandCollapseProject = new CommandID(GuidList.guidCollapseProjectCmdSet, (int)PkgCmdIDList.cmdidCollapseProject);
                MenuCommand menuItemProject = new MenuCommand(MenuItemCallback, menuCommandCollapseProject);
                mcs.AddCommand(menuItemProject);

                CommandID menuCommandCollapseProjectMulti = new CommandID(GuidList.guidCollapseSolutionCmdSetProjectMulti, (int)PkgCmdIDList.cmdidCollapseProjectMulti);
                MenuCommand menuItemProjectMulti = new MenuCommand(MenuItemCallback, menuCommandCollapseProjectMulti);
                mcs.AddCommand(menuItemProjectMulti);

                CommandID menuCommandCollapseSolutionNoSelection = new CommandID(GuidList.guidCollapseSolutionNoSelectionCmdSet, (int)PkgCmdIDList.cmdidCollapseTreeNoSelection);
                MenuCommand menuItemNoSelection = new MenuCommand(MenuItemCallbacNoSelection, menuCommandCollapseSolutionNoSelection);

                mcs.AddCommand(menuItemNoSelection);
            }
        }

        private void CollapseHierarchy()
        {
            object[] selection = GetSelectedUIHierarchy(SolutionExplorer);

            if (selection == null || selection.Length == 0)
            {
                return;
            }

            foreach (object selected in selection)
            {
                if (selected is UIHierarchyItem)
                {
                    UIHierarchyItem item = selected as UIHierarchyItem;

                    if (item != null)
                    {
                        item.DTE.SuppressUI = true;

                        // collapse each item in the hierarchy.
                        ProcessHierarchy(item);

                        // Select the solution/project node or else when you click on the solution window
                        // scrollbar, it will synchronize the open document with the tree and pop
                        // out the corresponding node.
                        item.Select(vsUISelectionType.vsUISelectionTypeSelect);

                        item.DTE.SuppressUI = false;
                    }
                }
            }
        }

        /// <summary>
        /// Collapses the hierarchy item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void CollapseHierarchyItem(UIHierarchyItem item)
        {
            // don't collapse a solution node because it would cause it to be re-drawn
            // and that takes a long time.
            if (item.UIHierarchyItems.Expanded && !(item.Object is Solution))
            {
                if (item.UIHierarchyItems.Expanded)
                {
                    item.UIHierarchyItems.Expanded = false;

                    if (item.UIHierarchyItems.Expanded)
                    {
                        item.Select(vsUISelectionType.vsUISelectionTypeSelect);

                        this.SolutionExplorer.DoDefaultAction();
                    }
                }
            }
        }

        /// <summary>
        /// Gets the selected UI hierarchy.
        /// </summary>
        /// <returns></returns>
        private object[] GetSelectedUIHierarchy(UIHierarchy solutionExplorer)
        {
            object[] selection = solutionExplorer.SelectedItems as object[];

            return selection;
        }

        private bool IsCommandExecutable()
        {
            bool executable = false;

            try
            {
                // Get the the Solution Explorer tree
                SolutionExplorer = Dte.ToolWindows.SolutionExplorer;

                // Check if there is any open solution
                if ((SolutionExplorer.UIHierarchyItems.Count > 0))
                {
                    executable = true;
                }
            }
            catch (Exception)
            {
                executable = false;
            }

            return executable;
        }

        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            if (!IsCommandExecutable())
                return;

            CollapseHierarchy();
        }

        private void MenuItemCallbacNoSelection(object sender, EventArgs e)
        {
            if (!IsCommandExecutable())
                return;

            // select the solution node
            SolutionExplorer.UIHierarchyItems.Item(1).Select(vsUISelectionType.vsUISelectionTypeSelect);

            CollapseHierarchy();
        }

        /// <summary>
        /// Processes the hierarchy.
        /// </summary>
        /// <param name="item">The item.</param>
        private void ProcessHierarchy(UIHierarchyItem item)
        {
            // now process each of the child nodes first
            foreach (UIHierarchyItem nestedItem in item.UIHierarchyItems)
            {
                ProcessHierarchy(nestedItem);
            }

            // next process the actual node item last.
            // if we do it first it won't collapse if it has child nodes that
            // are expanded.
            CollapseHierarchyItem(item);
        }
    }
}
